package com.zhuiyun.project.api.physician.service.serviceimpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.util.StringUtils;
import com.zhuiyun.project.api.addfriend.mapper.AddFriendMapper;
import com.zhuiyun.project.api.appuser.entity.User;
import com.zhuiyun.project.api.appuser.mapper.AppUserMapper;
import com.zhuiyun.project.api.friend.mapper.FriendMapper;
import com.zhuiyun.project.api.physician.entity.AppPhysician;
import com.zhuiyun.project.api.physician.entity.DoctorAudit;
import com.zhuiyun.project.api.physician.mapper.DoctorAuditMapper;
import com.zhuiyun.project.api.physician.mapper.PhysicianMapper;
import com.zhuiyun.project.api.physician.model.AppPhysicianModel;
import com.zhuiyun.project.api.physician.service.DoctorAuditService;
import com.zhuiyun.project.api.physician.service.PhysicianService;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.util.BeanUtils;
import com.zhuiyun.project.util.UploadFileUtils;
import com.zhuiyun.project.util.pageUtil.MybatisPageHelper;
import com.zhuiyun.project.util.pageUtil.PageRequest;
import com.zhuiyun.project.util.pageUtil.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UserServiceimpl
 * Description T0D0
 * Author Administrator
 * @Date 2023/6/5
 * Version 1.0
 **/
@Service
public class PhysicianServiceImpl implements PhysicianService {


    @Autowired
    UploadFileUtils uploadFileUtils;

    @Autowired
    PhysicianMapper physicianmapper;

    @Autowired
    AppUserMapper appUserMapper;
    @Autowired
    DoctorAuditService doctorAuditService;
    @Autowired
    DoctorAuditMapper doctorAuditMapper;
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private AddFriendMapper addFriendMapper;
    /**
     * @param doctorAudit
     * @Author kdj
     * @Description 审核不通过医师
     * @Date 2023/8/5 21:42
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    @Transactional
    public CommonResult requestNo(DoctorAudit doctorAudit) {
        //获取医师id
        Integer doctorId = doctorAudit.getDoctorId();
        //根据doctorId==userId修改user phy da对象
        int i;
        //修改医师表中数据
        i = physicianmapper.userToPhyNo(doctorId);
        if (i < 0) {
            return CommonResult.error();
        }
        //修改审核表中数据
        i = doctorAuditMapper.userToPhyNo(doctorId, doctorAudit.getAuditor(),doctorAudit.getAuditComment());
        if (i < 0) {
            return CommonResult.error();
        }
        return CommonResult.ok();
    }
    /**
     * @param id
     * @Author ys
     * @Description 根据医师id获取userid
     * @Date 2023/8/5 21:42
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public int getPhysicianUserid(int id) {
        int physicianUserid = physicianmapper.getPhysicianUserid(id);
        return physicianUserid;
    }

    /**
     * @param doctorAudit
     * @Author kdj
     * @Description 审核通过医师
     * @Date 2023/8/5 21:42
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    @Transactional
    public CommonResult requestOk(DoctorAudit doctorAudit) {
        //获取医师id
        Integer doctorId = doctorAudit.getDoctorId();
        //根据医师id删除所有好友
        friendMapper.delAllFriend(doctorId);
        //修改addFriend
        addFriendMapper.toPhy(doctorId);
        //根据doctorId==userId修改user phy da对象
        //修改user的类型
        int i;
        i = appUserMapper.userToPhy(doctorId);
        if (i < 0) {
            return CommonResult.error();
        }
        //修改医师表中数据
        i = physicianmapper.userToPhy(doctorId);
        if (i < 0) {
            return CommonResult.error();
        }
        //修改审核表中数据
        i = doctorAuditMapper.userToPhy(doctorId, doctorAudit.getAuditor());
        if (i < 0) {
            return CommonResult.error();
        }


        return CommonResult.ok();
    }

    /**
     * @param appPhysicianModel
     * @Author kdj
     * @Description 申请成为医师
     * @Date 2023/8/3 15:23
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    @Transactional
    public CommonResult insertPhysician(AppPhysicianModel appPhysicianModel) {
        //将appPhysicianModel转成appPhysicianLess格式
        AppPhysician appPhysicianLess = new AppPhysician();
        BeanUtils.copy(appPhysicianModel, appPhysicianLess);
        //转换job
        appPhysicianLess.setJob(appPhysicianModel.getJobBoolean() ? 1 : 2);
        //将生日转为年龄
        int age = DateUtil.ageOfNow(appPhysicianModel.getUserBirthday());
        //根据userId查询到appUser对象
        User user = appUserMapper.getUserInfo(appPhysicianModel.getUserId());
        //更新用户sex
        user.setImageId(appPhysicianModel.getImageId());
        user.setUpdateTime(new Date());
        user.setUserSex(appPhysicianModel.getUserSex());
        user.setUserBirthday(appPhysicianModel.getUserBirthday());
        user.setUserPhone(appPhysicianModel.getUserPhone());
        int i;
        i = appUserMapper.updateByPrimaryKeySelective(user);
        if (i < 0) {
            return CommonResult.error();
        }
        //更新医师对象
        appPhysicianLess.setDoctorAge(age);
        appPhysicianLess.setCreateTime(new Date());//设置创建时间
        appPhysicianLess.setUpdateTime(new Date());//设置修改时间
        appPhysicianLess.setDelFlag(0);//设置默认的删除时间
        appPhysicianLess.setAuditStatus(0);//设置默认的审核状态为0未进行处理
        i = physicianmapper.insertSelective(appPhysicianLess);
        //添加到doctor_audit
        i = doctorAuditService.insertPhyRecord(appPhysicianLess);
        return CommonResult.ok();
    }


    /**
     * @param userId
     * @Author kdj
     * @Description 获取医师的个人信息
     * @Date 2023/8/3 16:16
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult getPhyInfo(int userId) {
        //根据userId获取医师信息
        AppPhysicianModel app = physicianmapper.getPhyInfo(userId);
        // Format the Date as yyyy-MM-dd
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String userBirthday =null;
        if(app.getUserBirthday()!=null){
              userBirthday = dateFormat.format(app.getUserBirthday());
        }

        //返回类型
        Map map = new HashMap<>();
        //判断医师状态
        if (app.getAuditStatus() == null || app.getAuditStatus() == 2) {
            //如果为空的话 证明是第一个成为医师
            //返回性别 头像 生日 手机号
            //未通过的话  app.getAuditStatus() == null的内容
            map.put("userSex", app.getUserSex());
            map.put("imageId", app.getImageId());
            map.put("userName", app.getUserName());
            map.put("userBirthday", userBirthday);
            map.put("userPhone", app.getUserPhone());
            map.put("status", 2);
            return CommonResult.ok(map);
        } else if (app.getAuditStatus() == 1) {
            //此时已经是医师了
            //返回所有的字段  修改医师信息
            app.setJobBoolean(app.getJob() == 1 ? true : false);
            map = BeanUtil.beanToMap(app);
            map.put("status", 1);
            map.put("userBirthday", userBirthday);
            return CommonResult.ok(map);
        } else if (app.getAuditStatus() == 0) {
            //未处理状态
            //弹窗告知 然后关闭
            map.put("status", 0);
            map.put("text", "正在审核中...");
            map.put("userSex", app.getUserSex());
            map.put("imageId", app.getImageId());
            map.put("userName", app.getUserName());
            map.put("userBirthday", userBirthday);
            map.put("userPhone", app.getUserPhone());
            return CommonResult.ok(map);
        }
        return CommonResult.error();
    }

    /**
     * 根据用户名称获取用户信息
     *
     * @return java.util.List<com.zhuiyun.project.api.user.entity.User>
     * @author 温
     * @date 2023/6/5 18:04
     * @parameter [nickName, pageRequest]
     */
    @Override
    public PageResult physicianList(String doctorName, PageRequest pageRequest) {
        MybatisPageHelper.startPage(pageRequest);
        List<AppPhysicianModel> appPhysicians = physicianmapper.physicianList(doctorName);
        return MybatisPageHelper.getPageResult(appPhysicians);
    }


    /**
     * 医师管理查询
     *
     * @return com.zhuiyun.project.util.pageUtil.PageResult
     * @author 温
     * @date 2023/6/9 16:03
     * @parameter [nickName, pageRequest]
     */
    @Override
    public PageResult PhysicianListState(String queryUserName, PageRequest pageRequest) {
        MybatisPageHelper.startPage(pageRequest);
        List<AppPhysicianModel> appPhysicians = physicianmapper.PhysicianListState(queryUserName);
        return MybatisPageHelper.getPageResult(appPhysicians);
    }


    /**
     * 医师删除
     *
     * @return int
     * @author 温
     * @date 2023/6/11 21:41
     * @parameter [id]
     */
    @Override
    public int PhysicianUpdate(Integer id) {
        int i = physicianmapper.PhysicianUpdate(id);
        return i;
    }


    /**
     * @param file
     * @param file1
     * @param file2
     * @param appPhysicianModel
     * @Author kdj
     * @Description 修改医师信息
     * @Date 2023/8/5 10:40
     * @Return int
     */
    @Override
    @Transactional
    public CommonResult updatePhy(MultipartFile file, MultipartFile file1, MultipartFile file2, AppPhysicianModel appPhysicianModel) {
        //判断是否上传头像
        if (ObjectUtil.isNotEmpty(file)) {
            String s = UploadFileUtils.uploadAvatar(file);
            if (!StringUtils.isEmpty(s)) {
                appPhysicianModel.setImageId(Integer.valueOf(s));
            }
        }
        //判断是否上传个人照片
        if (ObjectUtil.isNotEmpty(file1)) {
            String s = UploadFileUtils.uploadAvatar(file1);
            if (!StringUtils.isEmpty(s)) {
                appPhysicianModel.setPersonalPhotos(Integer.valueOf(s));
            }
        }
        //判断是否上传执业照片
        if (ObjectUtil.isNotEmpty(file2)) {
            String s = UploadFileUtils.uploadAvatar(file2);
            if (!StringUtils.isEmpty(s)) {
                appPhysicianModel.setCertificatePhoto(Integer.valueOf(s));
            }
        }  //将appPhysicianModel转成appPhysicianLess格式
        AppPhysician appPhysicianLess = new AppPhysician();
        BeanUtils.copy(appPhysicianModel, appPhysicianLess);

        //将生日转为年龄
        int age = DateUtil.ageOfNow(appPhysicianModel.getUserBirthday());
        //根据userId查询到appUser对象
        User user = appUserMapper.getUserInfo(appPhysicianModel.getUserId());
        //更新用户sex
        user.setImageId(appPhysicianModel.getImageId());
        user.setUserName(appPhysicianModel.getUserName());
        user.setUpdateTime(new Date());
        user.setUserSex(appPhysicianModel.getUserSex());
        user.setUserBirthday(appPhysicianModel.getUserBirthday());
        user.setUserPhone(appPhysicianModel.getUserPhone());
        int i;
        i = appUserMapper.updateByPrimaryKeySelective(user);
        if (i < 0) {
            return CommonResult.error();
        }
        //更新医师对象
        appPhysicianLess.setDoctorAge(age);
        appPhysicianLess.setUpdateTime(new Date());//设置修改时间
        i = physicianmapper.updateByPrimaryKeySelective(appPhysicianLess);
        if (i < 0) {
            return CommonResult.error();
        }

        return CommonResult.ok();
    }
    /**
     * @param file
     * @param appPhysicianModel
     * @Author kdj
     * @Description 修改用户信息
     * @Date 2023/8/5 10:40
     * @Return int
     */
    @Override
    @Transactional
    public CommonResult updateUser(MultipartFile file, AppPhysicianModel appPhysicianModel) {
        //判断是否上传头像
        if (ObjectUtil.isNotEmpty(file)) {
            String s = UploadFileUtils.uploadAvatar(file);
            if (!StringUtils.isEmpty(s)) {
                appPhysicianModel.setImageId(Integer.valueOf(s));
            }
        }
        //将appPhysicianModel转成appPhysicianLess格式
        AppPhysician appPhysicianLess = new AppPhysician();
        BeanUtils.copy(appPhysicianModel, appPhysicianLess);
        //根据userId查询到appUser对象
        User user = appUserMapper.getUserInfo(appPhysicianModel.getUserId());
        //更新用户sex
        user.setImageId(appPhysicianModel.getImageId());
        user.setUserName(appPhysicianModel.getUserName());
        user.setUpdateTime(new Date());
        user.setUserSex(appPhysicianModel.getUserSex());
        user.setUserBirthday(appPhysicianModel.getUserBirthday());
        user.setUserPhone(appPhysicianModel.getUserPhone());
        int i;
        i = appUserMapper.updateByPrimaryKeySelective(user);
        if (i < 0) {
            return CommonResult.error();
        }
        return CommonResult.ok();
    }
    /**
     * @param file
     * @param file1
     * @param file2
     * @param appPhysicianModel
     * @Author kdj
     * @Description 后台添加医师信息
     * @Date 2023/8/5 14:27
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    @Transactional
    public CommonResult addPhy(MultipartFile file, MultipartFile file1, MultipartFile file2, AppPhysicianModel appPhysicianModel) {
        //判断是否上传头像
        if (ObjectUtil.isNotEmpty(file)) {
            String s = UploadFileUtils.uploadAvatar(file);
            if (!StringUtils.isEmpty(s)) {
                appPhysicianModel.setImageId(Integer.valueOf(s));
            }
        }
        //判断是否上传个人照片
        if (ObjectUtil.isNotEmpty(file1)) {
            String s = UploadFileUtils.uploadAvatar(file1);
            if (!StringUtils.isEmpty(s)) {
                appPhysicianModel.setPersonalPhotos(Integer.valueOf(s));
            }
        }
        //判断是否上传执业照片
        if (ObjectUtil.isNotEmpty(file2)) {
            String s = UploadFileUtils.uploadAvatar(file2);
            if (!StringUtils.isEmpty(s)) {
                appPhysicianModel.setCertificatePhoto(Integer.valueOf(s));
            }
        }  //将appPhysicianModel转成appPhysicianLess格式
        AppPhysician appPhysicianLess = new AppPhysician();
        BeanUtils.copy(appPhysicianModel, appPhysicianLess);

        //将生日转为年龄
        int age = DateUtil.ageOfNow(appPhysicianModel.getUserBirthday());
        //根据userId查询到appUser对象
        User user = new User();
        //更新用户sex
        user.setImageId(appPhysicianModel.getImageId());
        user.setUpdateTime(new Date());
        user.setUserName(appPhysicianModel.getUserName());
        user.setUserSex(appPhysicianModel.getUserSex());
        user.setUserBirthday(appPhysicianModel.getUserBirthday());
        user.setProhibition(0);
        user.setUserPhone(appPhysicianModel.getUserPhone());
        user.setCreateTime(new Date());
        user.setDelFlag(0);
        user.setLogOff("0");
        user.setUserType(0);
        int i;
        i = appUserMapper.insert(user);
        if (i < 0) {
            return CommonResult.error();
        }
        //更新医师对象
        appPhysicianLess.setUserId(user.getId());
        appPhysicianLess.setDoctorAge(age);
        appPhysicianLess.setCreateTime(new Date());//设置创建时间'
        appPhysicianLess.setUpdateTime(new Date());//设置修改时间'
        appPhysicianLess.setAuditStatus(0);//设置默认的审核状态为0未进行处理
        appPhysicianLess.setDelFlag(0);//设置默认的审核状态为0未进行处理
        i = physicianmapper.insertSelective(appPhysicianLess);
        if (i < 0) {
            return CommonResult.error();
        }
        //添加审核记录
        //添加到doctor_audit
        i = doctorAuditService.insertPhyRecord(appPhysicianLess);
        if (i < 0) {
            return CommonResult.error();
        }
        return CommonResult.ok();
    }

    /**
     * 查询注销的医生信息
     *
     * @return java.util.List<com.zhuiyun.project.api.physician.entity.AppPhysician>
     * @author 温
     * @date 2023/6/15 15:16
     * @parameter [doctorName, pageRequest]
     */
    public PageResult doctorLogOff(String doctorName, PageRequest pageRequest) {
        MybatisPageHelper.startPage(pageRequest);
        List<AppPhysician> appPhysicians = physicianmapper.doctorLogOff(doctorName, pageRequest);
        return MybatisPageHelper.getPageResult(appPhysicians);
    }

    /**
     * 恢复注销的医生账号
     *
     * @return int
     * @author 温
     * @date 2023/6/15 14:56
     * @parameter [id]
     */

    public int doctorRestore(int id) {
        int i = physicianmapper.doctorRestore(id);
        return i;
    }


    /**
     * 彻底删除注销的医生信息
     *
     * @return int
     * @author 温
     * @date 2023/6/15 15:07
     * @parameter [id]
     */

    public int doctorRestoreDelete(int id) {
        int i = physicianmapper.doctorRestoreDelete(id);
        return 0;
    }


}
